package com.homedroid.tasks;

import java.io.IOException;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;

import com.homedroid.dal.Client;
import com.homedroid.dal.Parser;

public class checkUpdatesTask extends AsyncTask<Void, String, Boolean> {
	private Context context;
	private Client client;
	private int versionint;

	public checkUpdatesTask(Context context, int versionint) throws IOException {
		this.versionint = versionint;
		this.context = context;
		client = new Client();

	}

	@Override
	protected void onPreExecute() {
		Log.i("AsyncTask", "onPreExecute");
	}

	@Override
	protected Boolean doInBackground(Void... params) { 
		boolean result = false;
		try {
			Log.i("AsyncTask", "doInBackground: Creating socket");

			if (client.nsocket.isConnected()) {

				Log.i("AsyncTask", "doInBackground: Socket created, streams assigned");
				Parser parser = new Parser();
				client.SendDataToNetwork(parser.checkUpdates(versionint));
		        boolean uptodate = Boolean.parseBoolean(parser.xmlread(client.ReceiveDataFromNetwork()));
		        if(!uptodate){
		        	this.publishProgress("Show the dialog");
		        }

			}
		} catch (IOException e) {

			Log.i("AsyncTask", "doInBackground: IOException");
			result = true;
		} catch (Exception e) {
			e.printStackTrace();
			Log.i("AsyncTask", "doInBackground: Exception");
			result = true;
		} finally {
			try {
				client.nsocket.close();
			} catch (IOException e) {
				e.printStackTrace();
				System.out.println("tot???");
			} catch (Exception e) {
				e.printStackTrace();
				System.out.println("tot?");
			}
			Log.i("AsyncTask", "doInBackground: Finished");
			result = true;

		}
		return result;
	}

	@Override
	protected void onProgressUpdate(String... values) {
		if (values.length > 0) {
			Log.i("AsyncTask", "onProgressUpdate: " + values[0]);
			
			AlertDialog infoDialog = new AlertDialog.Builder(context)
			.setTitle("Update available!")
			.setMessage("A new version of HomeDroid is online")
			.setPositiveButton("Download",new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog,	int which) {
					Intent intent = new Intent(Intent.ACTION_VIEW);
					intent.setData(Uri.parse("http://goo.gl/viNlX"));
					context.startActivity(intent);
				}
			
			}).create();
			infoDialog.show();
		}
	}

	@Override
	protected void onCancelled() {
		Log.i("AsyncTask", "Cancelled.");
	}

	@Override
	protected void onPostExecute(Boolean result) {
		if (result) {
			Log.i("AsyncTask - result=true", "Loading successfull");
		} else {
			 Log.i("AsyncTask - result=false", "Loading Error");
		}

	}

}
